package com.xstech.library.utils;

import static android.os.Environment.MEDIA_MOUNTED;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;

import com.nostra13.universalimageloader.utils.L;

import com.xstech.library.app.BaseApp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {
    private static final String MY_FOLDER = "XingshenTech";
    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

    public static File getAppDir() {
        File appCacheDir = null;
        String externalStorageState;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException e) {
            externalStorageState = "";
        }

        if (MEDIA_MOUNTED.equals(externalStorageState) && hasExternalStoragePermission(BaseApp.getApp())) {
            appCacheDir = getAppFile();
        }
        return appCacheDir;
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    public static File getAppFile() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), MY_FOLDER);
        if (!dataDir.exists()) {
            if (!dataDir.mkdirs()) {
                L.w("Unable to create external cache directory");
                return dataDir;
            }
            try {
                new File(dataDir, ".nomedia").createNewFile();
            } catch (IOException e) {
                L.i("Can't create \".nomedia\" file in application external cache directory");
            }
        }
        return dataDir;
    }

    private static String SDPATH = Environment.getExternalStorageDirectory() + "/"; // 获取 App 专属的外部存储目录

    public static String getSDPATH() {
        return SDPATH;
    }

    /**
     * 在SD卡上创建文件
     *
     * @throws IOException
     */
    public static File creatSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建文件
     *
     * @throws IOException
     */
    public static File creatSDFile(String path, String fileName) throws IOException {
        File file = new File(path + fileName);
        if (!file.exists())
            file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName
     */
    public static File creatSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdir();
        return dir;
    }

    /**
     * 判断SD卡上的文件夹是否存在
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

    /**
     * 将一个InputStream里面的数据写入到SD卡中
     */
    public static File write2SDFromInput(String path, String fileName,
                                         InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            creatSDDir(path);
            file = creatSDFile(path + fileName);
            output = new FileOutputStream(file);
            byte buffer[] = new byte[4 * 1024];
            while ((input.read(buffer)) != -1) {
                output.write(buffer);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    /**
     * 将一个String里面的数据写入到SD卡中
     */
    public static File write2SDFromInput(String path, String fileName, String input) {
        File file = null;
        OutputStream output = null;
        try {
            creatSDDir(path);
            file = creatSDFile(path + fileName);
            output = new FileOutputStream(file);
            output.write(input.getBytes());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /*
     * 写入到内部存储，只需要传文件名如：a.html
     * */
    public static void write2InnerStorage(String path, String str, Context context) {
        try {
            File file = context.getDir(path, Context.MODE_PRIVATE);
            file.mkdirs();
            //
            // FileOutputStream fos =
            // context.getApplicationContext().openFileOutput(path,Context.MODE_PRIVATE);
            // fos.write(str.getBytes());
            // fos.flush();
            // fos.close();

            file = new File(context.getFilesDir(), path);
            FileOutputStream fos = new FileOutputStream(file);

            fos.write(str.getBytes());
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 从内部存储读取，只需要传文件名如：a.html
     * */
    public static String readInnerFile(String path, Context context) {
        try {
            FileInputStream fis = context.openFileInput(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = -1;
            while ((len = fis.read(data)) != -1) {
                baos.write(data, 0, len);
            }
            return new String(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 保存图片到本地
     *
     * @param context
     * @param bitName
     * @param mBitmap
     * @return
     */
    public static File saveMyBitmap(Context context, String bitName, Bitmap mBitmap) {
        String fileName = "pic";
        if (!StringUtils.isEmpty(bitName)) {
            if (bitName.lastIndexOf("@") != -1) {
                fileName = bitName.substring(bitName.lastIndexOf("/"), bitName.lastIndexOf("@"));
            } else {
                fileName = bitName.substring(bitName.lastIndexOf("/"));
            }
        }
        File f;
        FileOutputStream fOut = null;
        try {
            f = FileUtils.creatSDFile(BaseApp.getApp().getDownloads(), fileName);
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fOut != null)
                try {
                    fOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(f));
        context.sendBroadcast(intent);
        MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStorageDirectory().getPath()
        }, null, null);

        return f;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 新建报表文件
     *
     * @param fileName
     * @return
     */
    public static String getReportPath(String fileName) {
        File filePath;
        if (getAppFile() == null) {
            return null;
        } else {
            filePath = new File(getAppFile().getAbsolutePath() + File.separator + "report");
        }

        if (!filePath.exists()) {
            filePath.mkdirs();
        }
//        File file = new File(filePath, fileName+".xls");
        return filePath.getAbsolutePath();
    }

    /**
     * 事务录音保存的地址
     *
     * @return
     */
    public static String getSheetRecordPathByCurrentTime() {
        File filePath = new File(getAppDir().getAbsolutePath() + File.separator + "sheet");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        File file = new File(filePath, "record_" + System.currentTimeMillis() + ".mp4");
        return file.getAbsolutePath();
    }

    /**
     * 聊天录音保存的地址
     *
     * @return
     */
    public static String getChatRecordPathByCurrentTime() {
        File filePath = new File(getAppDir().getAbsolutePath() + File.separator + "chat");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        File file = new File(filePath, "record_" + System.currentTimeMillis() + ".mp4");
        return file.getAbsolutePath();
    }

    /**
     * 聊天录音保存的地址
     *
     * @return
     */
    public static String getChatRecordPath() {
        File filePath = new File(getAppDir().getAbsolutePath() + File.separator + "chat");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        return filePath.getAbsolutePath();
    }
    /**
     * 删除所有事务录音
     */
    public static void deleteAllSheetAudioFile(){
        File[] files = new File(getAppDir().getAbsolutePath() + File.separator + "sheet" + File.separator + "voice").listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            file.delete();
        }
    }
    /**
     * 事务图片保存的路径
     *
     * @return
     */
    public static String getSheetPicsPath() {
        File filePath = new File(getAppDir().getAbsolutePath() + File.separator + "sheet" + File.separator + "pics");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        return filePath.getAbsolutePath();
    }

    /**
     * 删除所有图片
     */
    public static void deleteAllSheetPicsFile() {
        File[] files = new File(getSheetPicsPath()).listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            file.delete();
        }
    }


}
